<template>
  <div class="addAdvertise">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      size="default"
      status-icon
    >
      <el-form-item label="广告名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="广告位置" prop="type">
        <el-select v-model="ruleForm.type">
          <el-option label="PC首页轮播" :value="0" />
          <el-option label="App首页轮播" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="ruleForm.startTime"
          type="datetime"
          placeholder="请选择时间"
          clearable
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="到期时间" prop="endTime">
        <el-date-picker
          v-model="ruleForm.endTime"
          type="datetime"
          placeholder="请选择时间"
          clearable
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="上线/下线" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio :label="0">下线</el-radio>
          <el-radio :label="1">上线</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上线/下线" prop="status">
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="http://xue.cnkdl.cn:9082/mall-admin/minio/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          list-type="picture"
          :on-success="handleSuccess"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过100kb</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" />
      </el-form-item>
      <el-form-item label="广告链接" prop="url">
        <el-input v-model="ruleForm.url" />
      </el-form-item>
      <el-form-item label="广告备注" prop="note">
        <el-input
          v-model="ruleForm.note"
          type="textarea"
          placeholder="请输入内容"
          style="width: 60%"
          rows="6"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import * as http from "@/request/http";
import { onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
console.log("参数", route.query);
const { id } = route.query;
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadProps,
  type UploadUserFile,
} from "element-plus";

interface RuleForm {
  name: string;
  type: number;
  startTime: string;
  endTime: string;
  status: number;
  sort: number;
  url: string;
  note: string;
  pic: string;
}

// 实例
const ruleFormRef = ref<FormInstance>();
// 表单
let ruleForm = ref<RuleForm>({
  name: "",
  type: 1,
  startTime: "",
  endTime: "",
  status: 0,
  sort: 0,
  url: "",
  note: "",
  pic: "",
});

//图片的qpi
const fileList = ref<UploadUserFile[]>([]);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log("134删除触发", uploadFile, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (file) => {
  console.log("138二进制", file);
};

// 上传成功的回调
const handleSuccess: UploadProps["onSuccess"] = (uploadFile, uploadFiles) => {
  console.log("上传的回调", uploadFile.data);
  console.log("本地的回调", uploadFiles);
  ruleForm.value.pic = uploadFile.data.url;
};

const validatePass = (_rule: any, value: any, callback: any) => {
  const flg = /^(http|https):\/\/([\w-]+\.)+[\w]+(:\d+)?(\/.*)?$/;
  if (value === "") {
    callback(new Error("请输入地址"));
  } else if (!flg.test(value)) {
    callback(new Error("请填写正确格式"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "blur" }],
  endTime: [{ required: true, message: "请选择到期时间", trigger: "blur" }],
  url: [
    { required: true, message: "请输入广告链接", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
});

onMounted(async () => {
  //发送请求渲染要修改的数据
  const res = await http.advertise.getHomeAdvertise(id);
  const url = res.data.pic;
  const regex = /\/([^/]+)$/;
  const picName = regex.exec(url)!; //非空断言
  console.log();
  if (res.data.pic) {
    fileList.value.push({
      name: picName[1],
      url: res.data.pic,
    });
  }

  ruleForm.value = res.data;
  //   console.log(ruleForm);
});

// // 上传图片发生改变的钩子
// const handChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
//   console.log("发送的请求", uploadFile.response);
//   console.log("本地的数据", uploadFiles);
// };

// 判断条件通过之后触发
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log("图片", fileList.value[0]);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("是否提交数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          http.advertise
            .postAdvertiseUpdateId(id, ruleForm.value)
            .then((res) => {
              if (res.code === 200) {
                ElMessage.success("提交成功");
              } else {
                ElMessage.error("请重新提交");
              }
            })
            .catch((err) => {
              ElMessage.error("请重新提交", err);
            });
        })
        .catch(() => {
          ElMessage.error("取消提交");
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style lang="less" scoped>
.addAdvertise {
  width: 60%;
  margin: 50px auto;
  border: 2px solid #f5f5f5;
  padding: 50px 50px;
  .el-input {
    width: 60%;
  }
}
</style>
